<!--
 * @Author: LAB
 * @Date: 2021-05-18 11:40:44
 * @Description: 药品目录
 * @FilePath: \client-app\src\views\drug\drug.vue
-->
<template>
  <div>
    <div style="padding: 0 12px">
      <HisToolBar />
    </div>
    <div class="grup-body">
      <div>
        <div class="show-num">
          <p>当前显示数量为：<span>药品数量</span></p>
          <p>已隐藏启用/停用药品</p>
        </div>
        <Tree
          ref="treeRef"
          v-if="treeData && treeData.length > 0"
          v-bind="treeOptions"
          :items="treeData"
          @item-context-menu="treeItemContext"
          @edit="submitTreeItem"
          @item-click="selectItem"
          v-model:isEditId="treeIsEditId"
        ></Tree>
        <div v-else class="center pad-12">
          <DxButton v-bind="addTreeItemOptions" />
        </div>
        <Filter />
      </div>
      <DxSortable
        filter=".dx-row-lines"
        group="shared"
        data="listData"
        :allow-drop-inside-item="true"
      >
        <!-- @drag-end="onDragEnd" -->
        <DrugBase></DrugBase>
        <div style="margin-top: 10px" :style="getTabWidth(settingTabs.length)">
          <DxTabs :data-source="settingTabs" v-model:selected-index="openTab" />
        </div>
        <component :is="settingTabs[openTab].id"></component>
        <div
          style="margin-top: 10px"
          :style="getTabWidth(threeSettingTabs.length)"
        >
          <DxTabs
            :data-source="threeSettingTabs"
            v-model:selected-index="threeOpenTab"
          />
        </div>
        <component :is="threeSettingTabs[threeOpenTab].id"></component>
      </DxSortable>
    </div>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { ApiTool } from "@/api/api-tool";
import { Inject, Ref, Watch } from "vue-property-decorator";
import DataSource from "devextreme/data/data_source";
import notify from "devextreme/ui/notify";
import DxTabs from "devextreme-vue/tabs";
import { SearchByURL } from "@/utils/search-byurl";
import { RouteLocation } from "vue-router";
import { ApiExceptionShow } from "@/utils/api-exception-show";
import ThemeSwitch from "@/framework/theme-switch/theme-switch";
import { ViewTool } from "@/framework/utils/view-tool";
import DxSortable from "devextreme-vue/sortable";
import LoadElement from "@/framework/utils/load-element";
import Tree from "@/framework/components/tree/tree.vue";
// import { DictionaryClient, DrugSortTree } from "@/api/api_dictionaryclient";
import { GetPageListDictionaryInput } from "@/api/api_catalogclient";
import DrugBase from "./components/drug-base.vue";
import DrugSku from "./components/drug-sku.vue";
import { RightContextI } from "@/framework/components/right-menu/right-menu.vue";
import Filter from "./components/filter.vue";
import HisToolBar from "./components/tool-bar.vue";
import { DrugSortClient } from "@/api/api_drugclient";
import { dxTreeViewOptions } from "devextreme/ui/tree_view";
import { dxButtonOptions } from "devextreme/ui/button";
import DxButton from "devextreme-vue/button";
import { Tool } from "@/utils/tool";
import DrugTaboo from "./components/drug-taboo.vue";
import DrugAgree from "./components/drug-agree.vue";
import DrugMade from "./components/drug-made.vue";

let formData: any = {};
let self: any;
let searchByURL: SearchByURL;
const threeSettingTabs = [
  {
    id: "ProductType",
    text: "厂牌列表",
    content: "Comment tab content",
  },
  {
    id: "RepaySetting",
    text: "调价记录",
    content: "Find tab content",
  },
  {
    id: "Agreement",
    text: "成本价记录",
    content: "Find tab content",
  },
  {
    id: "Agreement",
    text: "存储设置",
    content: "Find tab content",
  },
  {
    id: "DrugAgree",
    text: "协定药品",
    content: "Find tab content",
  },
  {
    id: "DrugMade",
    text: "自制药品",
    content: "Find tab content",
  },
];
const settingTabs = [
  {
    id: "DrugSku",
    text: "药品规格",
    content: "DrugSku",
  },
  {
    id: "DrugTaboo",
    text: "配伍禁忌",
    content: "DrugTaboo",
  },
];
@Options({
  components: {
    DxSortable,
    Tree,
    DxTabs,
    DrugBase,
    DrugSku,
    Filter,
    HisToolBar,
    DxButton,
    DrugTaboo,
    DrugAgree,
    DrugMade,
  },
})
export default class Drug extends Vue {
  @Inject()
  apiTool: ApiTool;
  client: DrugSortClient;
  @Ref()
  treeRef: Tree;
  formData: any;
  tabItemWidth = 100; // tab宽度
  openTab = 0;
  settingTabs = settingTabs;
  getTabWidth(length) {
    let style = `width:${this.tabItemWidth * length}px`;
    return style;
  }

  threeOpenTab = 0;
  threeSettingTabs = threeSettingTabs;

  treeData: any[] = [];
  treeOptions: dxTreeViewOptions = {
    selectionMode: "single",
  };
  created() {
    self = this;
    this.client = this.apiTool.createClient(DrugSortClient);
    searchByURL = new SearchByURL(this.$router);
  }
  // testTreeItem: DrugSortTree = {
  //   drugSortId: "6660",
  //   name: "测试",
  //   parentId: "",
  // };
  async mounted() {
    document.addEventListener("rightContext", this.rightClick);
    this.treeData = await this.getTreeList();
  }
  beforeUnmount() {
    document.removeEventListener("rightContext", this.rightClick);
  }

  // 获取目录
  @Watch("drugSchemeId")
  async initTreeData(newVal) {
    if (newVal) {
      this.treeData = await this.getTreeList();
    }
  }

  // 方案id
  get drugSchemeId(): string {
    return (this.$route.query["drugSchemeId"] || "") as string;
  }
  // 根据方案id获取目录
  getTreeList() {
    if (!this.drugSchemeId) return null;
    return this.client.getListPageWithDrugSchemeId(this.drugSchemeId).then(
      (res) => {
        if (res.isSuccess) {
          let drugSortId = this.drugSortId;
          let parentId = "";
          if (res.listData.length > 0 && !drugSortId) {
            parentId = res.listData[0].parentId;
            drugSortId = res.listData[0].drugSortId;
            searchByURL.setParamsToUrl({
              drugSortId,
              parentId,
            });
          }
          let listData = this.treeListChangeSelect(drugSortId, res.listData);
          return listData;
        } else {
          notify(res.message, "error");
          return [];
        }
      },
      (err) => {
        ApiExceptionShow.showException(err, this);
        return [];
      }
    );
  }
  // 正在编辑的treeItemID
  treeIsEditId = "";
  // 药品数目录操作菜单
  rightMenu: any = [
    {
      text: "新增",
      id: "add",
      items: [
        {
          text: "同级分类",
          id: "addBrother",
        },
        {
          text: "子级分类",
          id: "addChild",
        },
      ],
    },
    {
      id: "edit",
      text: "修改",
    },
    {
      id: "remove",
      text: "删除",
    },
    {
      id: "print",
      text: "打印",
      items: [
        {
          id: "money",
          text: "价目表",
        },
        {
          id: "typeList",
          text: "品种清单",
        },
      ],
    },

    {
      id: "enable",
      text: "启用",
    },
    {
      id: "disable",
      text: "禁用",
    },
    {
      text: "显示",
      id: "show",
      items: [
        {
          id: "showDurgNum",
          text: "药品数量",
          radioGroup: "showNum",
        },
        {
          id: "showSku",
          text: "规格数量",
          radioGroup: "showNum",
        },
        {
          id: "showAbled",
          text: "启用",
          isCheckBox: true,
          value: true,
        },
        {
          id: "showDisabled",
          text: "停用",
          isCheckBox: true,
          value: false,
        },
      ],
    },
  ];
  @Inject()
  rightContextOption: RightContextI;
  // 右键菜单初始化
  rootValue = "00000000-0000-0000-0000-000000000000";
  treeItemContext(e) {
    this.rightContextOption.content = {
      id: "drugTree",
      event: e,
    };
    let { isEdit, type } = e;
    let rightMenu = this.rightMenu;
    // 顶级菜单
    if (e.parentId == this.rootValue) {
      rightMenu[0].items[0]["disabled"] = true;
    } else {
      rightMenu[0].items[0]["disabled"] = false;
    }
    // 是否允许编辑
    if (isEdit) {
      rightMenu = this.rightMenu.map((item) => {
        return {
          ...item,
          disabled: item.id == "edit" || item.id == "remove",
        };
      });
    }
    // 未分类
    rightMenu[0].items[1]["disabled"] = type == 4;
    this.rightContextOption.items = rightMenu;
  }
  // 右键菜单被点击
  rightClick(event: CustomEvent) {
    let { detail = {} } = event;
    let { itemData, content } = detail;
    if (content.id != "drugTree") {
      return;
    }
    let { coding, drugSchemeId, drugSortId, name, parentId } = content.event;
    switch (itemData.id) {
      case "addBrother":
        this.addTreeItem({
          drugSchemeId,
          parentId,
          name: "",
          drugSortId: "",
        });
        break;
      case "addChild":
        this.addTreeItem({
          drugSchemeId,
          parentId: drugSortId,
          name: "",
          drugSortId: "",
        });
        this.expandItem(drugSortId);
        break;
      case "edit":
        this.treeIsEditId = drugSortId;
        break;
      case "remove":
        this.client.delete(drugSortId).then(
          (res) => {
            if (res.isSuccess) {
              let parent = this.treeData.find((item) => {
                if (item.drugSortId == parentId) {
                  return item;
                }
              });
              searchByURL.setParamsToUrl({
                drugSortId: parentId,
                parentId: parent.drugSortId,
              });
              notify(res.message, "success");
              this.getTreeList().then((data) => {
                this.treeData = data;
              });
            } else {
              notify(res.message, "error");
            }
          },
          (err) => {
            ApiExceptionShow.showException(err, this);
          }
        );
        break;
      default:
        break;
    }
  }
  // 提交tree表单
  submitTreeItem(item) {
    if (!item.value) {
      // 添加且未输入名称删除添加item
      if (!item.data.drugSortId) {
        this.treeData = [].concat(this.deleteTreeItem(""));
      }
      return;
    }
    this.client
      .submit({
        ...item.data,
        name: item.value,
        drugSchemeId: this.drugSchemeId,
      })
      .then(
        async (res) => {
          if (res.isSuccess) {
            searchByURL.setParamsToUrl({
              drugSortId: res.data,
              parentId: item.data.parentId,
            });
            notify(res.message, "success");
            this.treeData = await this.getTreeList();
          } else {
            notify(res.message, "error");
          }
        },
        (err) => {
          ApiExceptionShow.showException(err, this);
        }
      );
  }
  // 删除数组单个元素
  deleteTreeItem(drugSortId: string, list = this.treeData) {
    console.log();
    
    list.forEach((ele, index) => {
      if (ele.drugSortId == drugSortId) {
        list.splice(index, 1);
      }
    });
    return list;
  }
  // tree添加按钮配置
  addTreeItemOptions: dxButtonOptions = {
    text: "新建目录",
    stylingMode: "contained",
    type: "default",
    onClick: () => {
      if (!self.drugSchemeId) {
        notify("请先选择方案");
        return;
      }
      self.addTreeItem({
        drugSchemeId: self.drugSchemeId,
        parentId: self.rootValue,
        name: "",
        drugSortId: "",
      });
    },
  };
  // 本地添加数据
  addTreeItem(addItem) {
    let treeData = this.treeData || [];
    treeData.splice(treeData.length, 0, addItem);
    this.treeData = Object.assign([], treeData);
  }
  // 页面刷新
  refresh() {
    this.$router.replace({ path: "/refresh" });
  }

  // 选中item drugSortId
  get drugSortId(): string {
    return (this.$route.query.drugSortId || "") as string;
  }
  // 初始化选择
  @Watch("drugSortId")
  initSelect(newVal) {
    this.treeData = this.treeListChangeSelect(newVal, this.treeData);
  }
  // 选中item
  selectItem(item) {
    let itemData = item.itemData;
    let { drugSortId = "", parentId = "", type = "" } = itemData;
    searchByURL.setParamsToUrl({
      drugType: type,
      drugSortId,
      parentId,
      filterCoding: "",
      filterName: "",
      filterDrugShortCode: "",
      drugIndex: "",
    });
    // this.treeData = this.treeListChangeSelect(drugSortId);
  }
  // 修改列表选中
  treeListChangeSelect(drugSortId: string, listData = this.treeData) {
    if (drugSortId) {
      listData = listData.map((item) => {
        if (item.drugSortId == drugSortId) {
          item["selected"] = true;
        } else {
          item["selected"] = false;
        }
        return item;
      });
    }
    listData = this.treeListExpand(drugSortId, listData);
    return listData;
  }
  // 展开指定目录
  expandItem(id: string) {
    this.treeData = this.treeData.map((item) => {
      if (item.drugSortId == id) {
        item.expanded = true;
      }
      return item;
    });
  }
  // 数据驱动展开列表
  treeListExpand(drugSortId: string, listData = this.treeData) {
    if (drugSortId) {
      let parents = Tool.getTreeParentsById(listData, {
        key: "drugSortId",
        id: drugSortId,
        parentKey: "parentId",
        rootValue: this.rootValue,
      });
      for (let item of listData) {
        item.expanded = false;
        for (let parn of parents) {
          if (parn.drugSortId == item.drugSortId) {
            item.expanded = true;
          }
        }
      }
    }
    return listData;
  }
}
</script>

<style scoped lang="scss">
.grup-body {
  display: flex;
  justify-content: space-evenly;
}
.header-input {
  input {
    padding: 0 !important;
  }
}
.show-num {
  line-height: 40px;
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  padding: 0 12px;
  font-size: 14px;
  p:last-child {
    font-size: 12px;
    color: #666;
    margin-bottom: 10px;
    line-height: 20px;
  }
  span {
    font-size: 16px;
    color: #24d361;
    font-weight: bold;
  }
}
</style>
